<template>
  <div class="paper-form">
    <div class="page-header">
      <h2>{{ isEdit ? '编辑论文' : '添加论文' }}</h2>
      <div>
        <el-button @click="$router.go(-1)">
          <el-icon><ArrowLeft /></el-icon>
          返回
        </el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          <el-icon><Check /></el-icon>
          {{ isEdit ? '更新' : '保存' }}
        </el-button>
      </div>
    </div>

    <el-card>
      <el-form 
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        size="default"
      >
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="论文名称" prop="paperTitle">
              <el-input 
                v-model="form.paperTitle" 
                placeholder="请输入论文名称"
                maxlength="200"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="期刊" prop="journal">
              <el-input 
                v-model="form.journal" 
                placeholder="请输入期刊名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检索级别" prop="indexLevel">
              <el-select 
                v-model="form.indexLevel" 
                placeholder="请选择检索级别"
                style="width: 100%"
              >
                <el-option label="SCI" value="SCI" />
                <el-option label="EI" value="EI" />
                <el-option label="CSSCI" value="CSSCI" />
                <el-option label="CSCD" value="CSCD" />
                <el-option label="其他" value="其他" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="期号" prop="issueNumber">
              <el-input 
                v-model="form.issueNumber" 
                placeholder="请输入期号"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="卷号" prop="volumeNumber">
              <el-input 
                v-model="form.volumeNumber" 
                placeholder="请输入卷号"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="页码" prop="pageNumbers">
              <el-input 
                v-model="form.pageNumbers" 
                placeholder="请输入页码"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="第一作者" prop="firstAuthor">
              <el-input 
                v-model="form.firstAuthor" 
                placeholder="请输入第一作者"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="通讯作者" prop="correspondingAuthor">
              <el-input 
                v-model="form.correspondingAuthor" 
                placeholder="请输入通讯作者"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="作者名单" prop="authorList">
              <el-input 
                v-model="form.authorList" 
                type="textarea"
                :rows="3"
                placeholder="请输入所有作者名单，多人用逗号分隔"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="发表日期" prop="publishDate">
              <el-date-picker
                v-model="form.publishDate"
                type="date"
                placeholder="请选择发表日期"
                style="width: 100%"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="影响因子" prop="impactFactor">
              <el-input-number 
                v-model="form.impactFactor" 
                :min="0"
                :precision="3"
                style="width: 100%"
                placeholder="请输入影响因子"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="论文链接" prop="paperLink">
              <el-input 
                v-model="form.paperLink" 
                placeholder="请输入论文链接（可选）"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft, Check } from '@element-plus/icons-vue'
import { paperAPI } from '@/api/paper'

export default {
  name: 'PaperForm',
  components: {
    ArrowLeft,
    Check
  },
  setup() {
    const route = useRoute()
    const router = useRouter()
    
    const formRef = ref()
    const submitting = ref(false)
    const isEdit = computed(() => !!route.params.id)
    
    const form = reactive({
      paperTitle: '',
      journal: '',
      issueNumber: '',
      volumeNumber: '',
      pageNumbers: '',
      indexLevel: '',
      authorList: '',
      firstAuthor: '',
      correspondingAuthor: '',
      publishDate: '',
      impactFactor: null,
      paperLink: ''
    })
    
    const rules = reactive({
      paperTitle: [
        { required: true, message: '请输入论文名称', trigger: 'blur' }
      ],
      journal: [
        { required: true, message: '请输入期刊名称', trigger: 'blur' }
      ],
      indexLevel: [
        { required: true, message: '请选择检索级别', trigger: 'change' }
      ],
      firstAuthor: [
        { required: true, message: '请输入第一作者', trigger: 'blur' }
      ],
      correspondingAuthor: [
        { required: true, message: '请输入通讯作者', trigger: 'blur' }
      ],
      authorList: [
        { required: true, message: '请输入作者名单', trigger: 'blur' }
      ],
      publishDate: [
        { required: true, message: '请选择发表日期', trigger: 'change' }
      ]
    })
    
    const loadPaperData = async () => {
      if (!isEdit.value) return
      
      try {
        const response = await paperAPI.getPaper(route.params.id)
        const paper = response.data
        
        Object.keys(form).forEach(key => {
          if (paper[key] !== undefined) {
            form[key] = paper[key]
          }
        })
      } catch (error) {
        console.error('加载论文数据失败:', error)
        ElMessage.error('加载论文数据失败')
        router.go(-1)
      }
    }
    
    const handleSubmit = async () => {
      try {
        await formRef.value.validate()
        
        submitting.value = true
        
        if (isEdit.value) {
          await paperAPI.updatePaper(route.params.id, form)
          ElMessage.success('更新成功')
        } else {
          await paperAPI.createPaper(form)
          ElMessage.success('创建成功')
        }
        
        router.push('/papers/list')
      } catch (error) {
        if (error.message) {
          console.error('提交失败:', error)
          ElMessage.error(error.message || '提交失败')
        }
      } finally {
        submitting.value = false
      }
    }
    
    onMounted(() => {
      loadPaperData()
    })
    
    return {
      formRef,
      form,
      rules,
      submitting,
      isEdit,
      handleSubmit
    }
  }
}
</script>

<style lang="scss" scoped>
.paper-form {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h2 {
      margin: 0;
      color: #303133;
    }
  }
  
  .el-form {
    .el-form-item {
      margin-bottom: 22px;
    }
  }
}
</style>
